package com.example.newfragment;

import java.lang.reflect.Type;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.boyuan.huijiaoyu.R;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.magicsoft.app.entity.CaseDetailEntity;
import com.magicsoft.app.entity.EmployeeRightsEntity;
import com.magicsoft.app.entity.RememberEntity;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.TokenHelper;
import com.magicsoft.app.wcf.AsyncHttpServiceHelper;
import com.magicsoft.app.wcf.BaseService;
import com.magicsoft.app.wcf.listener.GetMultilParamsListener;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.app.wcf.listener.GetTwoRecordListener;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;
import com.magicsoft.weitown.fragment.HomeList;

/**
 * 首页请求接口
 * 
 * @author cheng
 * 
 */
public class HomeService extends BaseService {

	public HomeService(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	// 获取Case详情
	public void GetCaseDetail(String cid, String corp_id,
			final GetMultilParamsListener listener) {

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.CASES + getParamString + "&cid=" + cid
				+ "&corp_id=" + corp_id;
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				try {
					String code = response.getString("code");
					if ("0".equals(code)) {
						JSONObject content = response.getJSONObject("content");
						Type type = new TypeToken<CaseDetailEntity>() {
						}.getType();
						CaseDetailEntity caseDetailEntity = gson.fromJson(
								content.toString(), type);
						if (listener != null) {
							listener.onFinish(caseDetailEntity);
						}
					} else {
						if (listener != null) {
							String message = response.getString("message");
							listener.onFailed(message);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				super.onSuccess(statusCode, headers, response);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});

	}
	
	//获取case和im
	public void getCaseAndIm(String cid, final GetMultilParamsListener listener){
		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.CASESANDIM + getParamString + "&cid=" + cid;
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				try {
					String code = response.getString("code");
					if ("0".equals(code)) {
						JSONObject content = response.getJSONObject("content");
						Type type = new TypeToken<CaseDetailEntity>() {
						}.getType();
						CaseDetailEntity caseDetailEntity = gson.fromJson(
								content.toString(), type);
						if (listener != null) {
							listener.onFinish(caseDetailEntity);
						}
					} else {
						if (listener != null) {
							String message = response.getString("message");
							listener.onFailed(message);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				super.onSuccess(statusCode, headers, response);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});
	}

	/**
	 * 消息推送post请求注册RegistrationID
	 */
	public void sendUsernameAndRegistrationID(String lat, String lng,
			String registrationId) {

		RequestParams params = new RequestParams();

		String getParamString = "";

		try {//
			params = TokenHelper.FetchColourTokenDelregistrationId(context,
					true, lat, lng, registrationId);
		} catch (Exception e) {
		}
		String requestUrl = Constant.EMPLOYEE_Jpush + getParamString;
		AsyncHttpServiceHelper.post(requestUrl, params,
				new JsonHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						super.onSuccess(statusCode, headers, response);
						try {
							String code = response.getString("code");
							String message = response.getString("message");
							if ("0".equals(code)) {
								Log.e("HomeService", "message = 注册RegId"
										+ message);
							} else {
								Log.e("HomeService", "message = 注册RegId"
										+ message);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, responseString,
								throwable);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

	/**
	 * 获取用户首页列表
	 */
	public void getNewEmployeeRight(String username, String page_num,
			String page_size,
			final GetOneRecordListener<List<HomeList>> listener) {

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.EMPLOYEE_HomeList + getParamString
				+ "&username=" + username + "&page_size=" + page_size
				+ "&page_num=" + page_num;

		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);
				try {
					String code = response.getString("code");
					String message = response.getString("message");
					if ("0".equals(code)) {
						JSONArray content = response.getJSONArray("content");
						Type type = new TypeToken<List<HomeList>>() {
						}.getType();
						List<HomeList> homelist = gson.fromJson(
								content.toString(), type);
						if (listener != null) {
							listener.onFinish(homelist);
						}
					} else {
						if (listener != null)
							listener.onFailed(message);
					}

				} catch (Exception e) {

					if (listener != null)
						listener.onFailed(context.getResources().getString(// JSON
																			// 解析错误
								R.string.json_analysis_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, responseString, throwable);
				if (listener != null){
//					listener.onFailed(context.getResources().getString(
//							R.string.network_connections_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));
			}
		});

	}

	/**
	 * 获取用户应用权限
	 */
	public void getEmployeeRight(
			final GetOneRecordListener<List<EmployeeRightsEntity>> listener) {

		RememberEntity rememberEntity = SharePreferenceHelper
				.GetRememberEntity(context);
		String username = rememberEntity.getAdmin();
		String password = rememberEntity.getPsw();

		RequestParams params = new RequestParams();
		params.put("loginUsername", username);
		params.put("loginPassword", password);

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.EMPLOYEE_RIGHTS + getParamString;

		AsyncHttpServiceHelper.post(requestUrl, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						// TODO Auto-generated method stub
						super.onSuccess(statusCode, headers, response);
						try {

							String code = response.getString("code");
							String message = response.getString("message");
							if ("0".equals(code)) {
								JSONArray rightsArray = response
										.getJSONArray("content");
								Type employeeType = new TypeToken<List<EmployeeRightsEntity>>() {
								}.getType();
								List<EmployeeRightsEntity> employeeResps = gson
										.fromJson(rightsArray.toString(),
												employeeType);

								if (listener != null) {
									listener.onFinish(employeeResps);
								}
							} else {
								if (listener != null)
									listener.onFailed(message);
							}

						} catch (Exception e) {

							if (listener != null)
								listener.onFailed(context.getResources()
										.getString(// JSON
													// 解析错误
												R.string.json_analysis_wrong));
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, responseString,
								throwable);
						if (listener != null)
							listener.onFailed(context.getResources().getString(
									R.string.network_connections_wrong));

					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
						if (listener != null)
							listener.onFailed(context.getResources().getString(
									R.string.network_connections_wrong));
					}
				});

	}

	/**
	 * 获取用户应用权限
	 */
	public void getAuth(String clientCode,
			final GetTwoRecordListener<String, String> listener) {

		RememberEntity rememberEntity = SharePreferenceHelper
				.GetRememberEntity(context);
		String username = rememberEntity.getAdmin();
		String password = rememberEntity.getPsw();

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.AUTH + getParamString + "&username="
				+ username + "&clientCode=" + clientCode;

		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);
				try {

					String code = response.getString("code");
					String message = response.getString("message");
					if ("0".equals(code)) {
						JSONObject contentObject = response
								.getJSONObject("content");

						String openID = contentObject.getString("openID");
						String accessToken = contentObject
								.getString("accessToken");
						if (listener != null) {
							listener.onFinish(openID, accessToken);
						}
					} else {
						if (listener != null)
							listener.onFailed(message);
					}

				} catch (Exception e) {

					if (listener != null)
						listener.onFailed(context.getResources().getString(// JSON
																			// 解析错误
								R.string.json_analysis_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, responseString, throwable);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));
			}
		});

	}

	/*
	 * 首页列表删除请求
	 */
	public void deleteHomelist(String usernames, String source_id, String comefrom,
			final PostRecordResponseListener listener) {

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourTokenDelHomeList(context,
					source_id, true);
		} catch (Exception e) {
		}

		String requestUrl = Constant.EMPLOYEE_HomeList + getParamString
				+ "&comefrom=" + comefrom +"&usernames="+usernames;
		Log.e("HomeService", "requestUrl = " + requestUrl);
		AsyncHttpServiceHelper.delete(requestUrl,
				new JsonHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						super.onSuccess(statusCode, headers, response);
						try {
							String code = response.getString("code");
							String message = response.getString("message");
							if ("0".equals(code)) {
								if (listener != null) {
									listener.onFinish(message);
								}
							} else {
								if (listener != null) {
									listener.onFailed(message);
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						super.onFailure(statusCode, headers, responseString,
								throwable);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

	// 修改个人信息
	public void changePersonInfo(String ChangeInfoJson,
			final PostRecordResponseListener listener) {
		String requestUrl = Constant.EMPLOYEE + "?";
		RequestParams params = new RequestParams();

		try {//
			params = TokenHelper.fetchColourTokenChangePersoninfo(context,
					true, ChangeInfoJson);
		} catch (Exception e) {
		}

		AsyncHttpServiceHelper.put(requestUrl, params,
				new JsonHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						try {
							String code = response.getString("code");
							String message = response.getString("message");
							if ("0".equals(code)) {
								if (listener != null) {
									listener.onFinish(message);
								}
							} else {
								if (listener != null) {
									listener.onFailed(message);
								}
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
						super.onSuccess(statusCode, headers, response);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						super.onFailure(statusCode, headers, responseString,
								throwable);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

}
